package com.qingcheng.task;

import com.qingcheng.dao.SeckillGoodsMapper;
import com.qingcheng.pojo.seckill.SeckillGoods;
import com.qingcheng.pojo.seckill.SeckillOrder;
import com.qingcheng.pojo.seckill.SeckillStatus;
import com.qingcheng.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MultiThreadingCreateOrder {

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IdWorker idWorker;

    @Async //异步执行声明
    public void createOrder() {
        try {
            System.out.println("准备执行--------");
            Thread.sleep(10000);
            SeckillStatus seckillStatus = (SeckillStatus) redisTemplate.boundListOps("SeckillOrderQueue").rightPop();
            if(seckillStatus != null) {
                String time = seckillStatus.getTime();
                Long id = seckillStatus.getGoodsId();
                String userName = seckillStatus.getUsername();

                //从redis中获取商品信息
                SeckillGoods goods = (SeckillGoods) redisTemplate.boundHashOps("SeckillGoods_" + time).get(id);
                //判断是否有商品
                if(goods==null || goods.getStockCount()<=0) { //没商品
                    throw new RuntimeException("已售罄!");
                }
                //有商品
                SeckillOrder seckillOrder = new SeckillOrder();
                seckillOrder.setId(idWorker.nextId());
                seckillOrder.setSeckillId(id);
                seckillOrder.setMoney(goods.getCostPrice());
                seckillOrder.setUserId(userName);
                seckillOrder.setSellerId(goods.getSellerId());
                seckillOrder.setCreateTime(new Date());
                seckillOrder.setStatus("0");
                //存入redis中
                redisTemplate.boundHashOps("SeckillOrder").put(userName,seckillOrder);
                //减少库存
                goods.setStockCount(goods.getStockCount()-1);
                //判断当前商品是否还有库存
                if(goods.getStockCount()<=0) {
                    //没库存,数据库更新,清除redis中的商品
                    seckillGoodsMapper.updateByPrimaryKeySelective(goods);
                    redisTemplate.boundHashOps("SeckillGoods_" + time).delete(id);
                }else {
                    //有库存,把更新后的库存数据覆盖掉之前的
                    redisTemplate.boundHashOps("SeckillGoods_" + time).put(id,goods);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
